#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangcong
# Email:zc_92@sina.com

import os
import time

from conf import settings

import requests

from requests.exceptions import ConnectionError


class ADSL(object):
    """
    ADSL拨号，断开连接
    """
    def __init__(self):
        """
        初始化adsl名称、用户名、密码
        """
        self.name = settings.ADSL_NAME   # ADSL名称
        self.username = settings.ADSL_USER  # ADSL用户名
        self.password = settings.ADSL_PWD  # ADSL密码ß

    def connect(self):
        """
        宽带拨号
        :return: None
        """
        while True:
            cmd_str = "rasdial %s %s %s" % (self.name, self.username, self.password)
            print(cmd_str)
            result = os.popen(cmd_str)
            if "命令已完成" in result.read():
                print("连接成功")
                break
            else:
                print("拨号连接失败，休息5秒，等待重新连接")
                time.sleep(5)
        # # time.sleep(10)
        # # print(self.network_test())
        # try:
        #     if not self.network_test():
        #         self.reconnect()
        #     else:
        #         print("连接成功")
        # except ConnectionError:
        #     self.reconnect()


    def disconnect(self):
        """
        断开宽带连接
        :return: None
        """
        cmd_str = "rasdial %s /disconnect" % self.name
        print(cmd_str)
        os.system(cmd_str)
        time.sleep(1)

    def reconnect(self):
        """
        重新进行拨号
        :return: None
        """
        print("-" * 20 + "> 重新拨号")
        self.disconnect()
        self.connect()

    def network_test(self):
        url = "http://www.baidu.com/"
        print('network_test url -->', url)
        ret = requests.head(url)
        print(ret.status_code, type(ret.status_code))
        if ret.status_code == 200:
            return True
        else:
            return False


